function testFN(fn, args) { //测试
	console.log(fn(...args));;
}

const styleObj2Str = (obj) => { //{zIndex:100,color:"#FFF"} =>'z-index:100;color:#FFF'
	let result = '';
	for (let key in obj) {
		let tempKey = '';

		for (let i = 0; i < key.length; i++) {
			// tempKey = tempKey + ((isNaN(key[i])&&(key[i] == key[i].toUpperCase()))? ("-"+key[i].toLowerCase()):key[i]);
			tempKey = tempKey + ((/[A-Z]/.test(key[i])) ? ("-" + key[i].toLowerCase()) : key[i]);
		};
		result += `${tempKey}:${obj[key]};`
	};
	return result
};

const formatTime = date => { //date=>'2022/07/13 21:50:55'
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => n.toString().padStart(2, "0"); //1=>01

const Adapt = function (e) { //微信小程序获取当前屏幕大小,注意:获取到的是px而非rpx
	let imageSize = {}
	let imgH = '',
		topT = ''
	uni.getSystemInfo({
		success: function (res) {
			console.log(res)
			let ratio = res.windowWidth / e.detail.width,
				imgW = res.windowWidth
			if (res.windowWidth > e.detail.width) {
				imgH = e.detail.height / ratio;
			} else {
				imgH = e.detail.height * ratio;
			}
			if (res.windowHeight > imgH) {
				let t = res.windowHeight - imgH

				topT = t / 2
				console.log(topT)
			}
			imageSize = {
				imageHeight: imgH,
				imageWidth: imgW,
				topT: topT
			}
		}
	})
	return imageSize
}

function getAge(strAge) { //根据出生日期 计算岁数
	if (!strAge) return '';
	//2021-06-20 09:23:12
	strAge = strAge.length == 10 ? strAge : strAge.slice(0, 10);
	var birArr = strAge.split("-");
	var birYear = birArr[0];
	var birMonth = birArr[1];
	var birDay = birArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1; //记得加1
	var nowDay = d.getDate();
	var returnAge;

	if (birArr == null) {
		return false
	};
	var d = new Date(birYear, birMonth - 1, birDay);
	if (d.getFullYear() == birYear && (d.getMonth() + 1) == birMonth && d.getDate() == birDay) {
		if (nowYear == birYear) {
			returnAge = 0; // 
		} else {
			var ageDiff = nowYear - birYear; // 
			if (ageDiff > 0) {
				if (nowMonth == birMonth) {
					var dayDiff = nowDay - birDay; // 
					if (dayDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				} else {
					var monthDiff = nowMonth - birMonth; // 
					if (monthDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				}
			} else {
				return "出生日期晚于今天，数据有误"; //返回-1 表示出生日期输入错误 晚于今天
			}
		}
		return returnAge;
	} else {
		return ("输入的日期格式错误！");
	}
}

function num2weekDay(num) { //数字转周几
	let str = "日一二三四五六";
	return str[num] ? `周${str[num]}` : '';
}

const getDateToNewData = (diffValue) => { //根据时间 计算距离当前时间
	if (diffValue) {
		return ""
	};
	//2021-06-20 09:23:12
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(diffValue.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateEnd = new Date(); //获取当前时间
	var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
	var monthC = Math.floor(dateDiff / (24 * 3600 * 1000 * 30)); //计算出相差月数
	var leaveMon = dateDiff % (24 * 3600 * 1000 * 30); //计算月数后剩余的毫秒数
	var weekC = Math.floor(leaveMon / (24 * 3600 * 1000 * 7)); //计算出相差星期数
	var leaveWeek = leaveMon % (24 * 3600 * 1000 * 7); //计算星期数剩余的毫秒数
	var dayC = Math.floor(leaveWeek / (24 * 3600 * 1000)); //计算出相差天数
	var leave1 = leaveWeek % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	var timesString = '';
	if (monthC != 0) {
		if (monthC > 6) {
			var timearr = diffValue.substring(0, 10).split("-");
			var timestrS = "" + timearr[0] + "年" + timearr[1] + "月" + timearr[2] + "日"
			timesString = timestrS
		} else if (monthC == 6) {
			timesString = '半年前'
		} else if (monthC < 6) {
			timesString = monthC + '月之前'
		}
	} else if (monthC == 0 && weekC != 0) {
		timesString = weekC + '周之前';
	} else if (weekC == 0 && dayC != 0) {
		timesString = dayC + '天之前';
	} else if (dayC == 0 && hours != 0) {
		timesString = hours + '小时之前';
	} else if (hours == 0 && minutes != 0) {
		timesString = minutes + '分钟之前';
	}
	return timesString;
}

function getAstro(date) { //判断星座
	//2021-06-20 09:23:12
	var date2 = new Date(date);
	var month = date2.getMonth() + 1
	var day = date2.getDate()
	// var s="魔羯⽔瓶双鱼牡⽺⾦⽜双⼦巨蟹狮⼦处⼥天秤天蝎射⼿魔羯";
	var s = "摩羯水瓶双鱼白羊金牛双子巨蟹狮子处女天枰天蝎射手摩羯";
	var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
	return s.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2);
}

function easyToast(title, icon = "none") { //微信小程序提示
	uni.showToast({
		icon,
		title
	});
}

function throttle(fn, interval) { //函数节流
	var enterTime = 0; //触发的时间
	var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
	return function () {
		var context = this;
		var backTime = new Date(); //第一次函数return即触发的时间
		if (backTime - enterTime > gapTime) {
			fn.call(context, ...arguments);
			enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
		}
	};
}

function debounce(fn, interval) { //函数防抖
	var timer;
	var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
	return function () {
		clearTimeout(timer);
		var context = this;
		var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
		timer = setTimeout(function () {
			fn.call(context, ...args);
		}, gapTime);
	};
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 * idx ,循环第几次，用&拼接
 * return URL参数字符串
 */
var urlEncode = (param, idx, key, encode) => {
	if (param == null) return '';
	var paramStr = '';
	var t = typeof (param);
	if (t == 'string' || t == 'number' || t == 'boolean') {
		var one_is = idx < 3 ? '?' : '&';
		paramStr += one_is + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
	} else {
		for (var i in param) {
			var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
			idx++
			paramStr += urlEncode(param[i], idx, k, encode);
		}
	}
	return paramStr;
}

var deCodeUrl = (params) => { //enCode=>deCode
	if (undefined === params || null === params) {
		return '';
	};
	let d = decodeURIComponent;
	return (typeof params === "object") ? JSON.parse(d(JSON.stringify(params))) : d(params);
}

function rpx2px(rpx, deviceWidth) { //rpx转px
	deviceWidth = deviceWidth ? deviceWidth : uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	let px = (deviceWidth / 750) * Number(rpx)
	return Math.floor(px);
}

function px2rpx(px, deviceWidth) { //px转rpx
	// deviceWidth = deviceWidth?deviceWidth: uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	let rpx = (750 / deviceWidth) * Number(px)
	return Math.floor(rpx);
}

function editStr(oldStr, index, str) { //编辑STR
	return oldStr.slice(0, index) + str + oldStr.slice(index);
}

function myTypeOf(obj) { //判断数据类型
	return Object.prototype.toString.call(obj).slice(8, -1);
}

function getNode(wxRef = uni, selector, isAll = false) { //获取节点信息
	let str = isAll ? "selectAll" : 'select';
	return new Promise((resolve, reject) => {
		wxRef.createSelectorQuery()[str](selector).boundingClientRect((res) => {
			if (res) {
				resolve(res);
			} else {
				reject("找不到该节点");
			}
		}).exec();
	})
}

function randomNum(minNum, maxNum) { //生成随机数,区间为[minNum,maxNum]
	minNum = Math.floor(minNum);
	maxNum = Math.floor(maxNum);
	switch (arguments.length) {
		case 1:
			maxNum = minNum;
			minNum = 0;
		case 2:
			if (maxNum < minNum) [minNum, maxNum] = [maxNum, minNum];
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
		default:
			return 0;
	}
}


function isParentNodeEl(obj, parentObj) { //判断dom子节点
	while (obj != undefined && obj != null && obj.tagName?.toUpperCase() != 'BODY') {
		if (obj == parentObj) {
			return true;
		}
		obj = obj.parentNode;
	}
	return false;
}

function getCursortPosition(ctrl) { //获取光标位置
	//获取光标位置函数 
	var CaretPos = 0;
	// IE Support
	if (document.selection) {
		ctrl.focus(); // 获取焦点
		var Sel = document.selection.createRange(); // 创建选定区域
		Sel.moveStart('character', -ctrl.value.length); // 移动开始点到最左边位置
		CaretPos = Sel.text.length;                      // 获取当前选定区的文本内容长度
	}
	// Firefox support 
	else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
		CaretPos = ctrl.selectionStart; // 获取选定区的开始点 
	}
	return CaretPos;
}


function setCaretPosition(ctrl, pos) { //设置光标位置
	console.log({ ctrl, pos });
	//设置光标位置函数 
	if (ctrl.setSelectionRange) {
		ctrl.focus();  // 获取焦点
		ctrl.setSelectionRange(pos, pos);  //设置选定区的开始和结束点
	}
	else if (ctrl.createTextRange) {

		var range = ctrl.createTextRange();  // 创建选定区
		range.collapse(true);                // 设置为折叠,即光标起点和结束点重叠在一起
		range.moveEnd('character', pos);     // 移动结束点
		range.moveStart('character', pos);   // 移动开始点
		range.select();                      // 选定当前区域
	}
}

function uint8ArrayToString(utf8EncodedData, codeType = "UTF-8") { //Uint8Array 转 字符串
	console.log("uint8ArrayToString");
	console.log({ utf8EncodedData, codeType });
	// 常见的编码格式有ASCII、ANSI、GBK、GB2312、UTF-8、GB18030和UNICODE等
	return (new TextDecoder(codeType)).decode(utf8EncodedData);
}

function stringToUint8Array(str) { //字符串 转 Uint8Array
	return (new TextEncoder()).encode(str);
}

function isCollision_rect(rect1, rect2) { //判断两个矩形是否碰撞
	let { offsetHeight, offsetLeft, offsetTop, offsetWidth } = rect1;
	let px1 = rect2.offsetLeft;
	let px2 = rect2.offsetLeft + rect2.offsetWidth;
	let py1 = rect2.offsetTop;
	let py2 = rect2.offsetTop + rect2.offsetHeight;
	let minX = (px1 - px2) > 0 ? px2 : px1;
	let maxX = (px1 - px2) > 0 ? px1 : px2;
	let minY = (py1 - py2) > 0 ? py2 : py1;
	let maxY = (py1 - py2) > 0 ? py1 : py2;

	let arr = [
		{ x: offsetLeft, y: offsetTop },
		{ x: offsetLeft + offsetWidth, y: offsetTop },
		{ x: offsetLeft + offsetWidth, y: offsetTop + offsetHeight },
		{ x: offsetLeft, y: offsetTop + offsetHeight },
		// { x: offsetLeft + offsetWidth / 2, y: offsetTop + offsetHeight / 2 },
		{ x: offsetLeft + offsetWidth / 2, y: offsetTop },
		{ x: offsetLeft + offsetWidth, y: offsetTop + offsetHeight / 2 },
		{ x: offsetLeft + offsetWidth / 2, y: offsetTop + offsetHeight },
		{ x: offsetLeft, y: offsetTop + offsetHeight / 2 },
	];

	let condition1 = arr.some(({ x, y }) => x >= minX && x <= maxX && y >= minY && y <= maxY);
	let condition2 = (offsetLeft >= minX) && (offsetLeft + offsetWidth <= maxX) && (offsetTop <= minY) && (offsetTop + offsetHeight >= maxY);
	let condition3 = (offsetLeft <= minX) && (offsetLeft + offsetWidth >= maxX) && (offsetTop >= minY) && (offsetTop + offsetHeight <= maxY);
	return condition1 || condition2 || condition3;
}

exports.tools = {
	imgPath: "",
	isCollision_rect,
	styleObj2Str,
	formatTime,
	formatNumber,
	Adapt,
	getAge,
	num2weekDay,
	getDateToNewData,
	getAstro,
	easyToast,
	throttle,
	debounce,
	urlEncode,
	deCodeUrl,
	rpx2px,
	px2rpx,
	editStr,
	myTypeOf,
	getNode,
	randomNum,
	isParentNodeEl,
	getCursortPosition,
	setCaretPosition,
	uint8ArrayToString,
	stringToUint8Array
}
